package Utility;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;

import Messages.Message;
import Messages.MessageType;

public class CheckPrepareProposalValue {
	FileUtilities fileUtilities;

	/**
	 * Get the highest ProposalId and Value
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public Message checkMyFileForProposalValue(String filePath,Message message){
		// The content will be in format N,V
		String fileContent = null;
		Message returnMessage = new Message();
		try {
			File f = new File(filePath);
			if(!f.exists()){
				f.createNewFile();
				System.out.println("reading values from file : " + filePath);
				System.out.println("Received Proposal ID : " + message.getProposalNumber() + " with Lock value :" + message.getLockValue());
				fileContent = message.getProposalNumber()+ ","+ message.getLockValue();
				FileUtilities.writeToFile(filePath, fileContent,false);
				returnMessage.setMessageType(MessageType.PROMISE_ACK);
				returnMessage.setProposalNumber(message.getProposalNumber());
				returnMessage.setLockValue(message.getLockValue());

			}else {
				fileContent = fileUtilities.readFileAsString(filePath);
				String[] proposalAndLockValue = fileContent.split(",");
				if(message.getProposalNumber() >= Integer.parseInt(proposalAndLockValue[0]))
				{
					fileContent = message.getProposalNumber()+ ","+ message.getLockValue();
					FileUtilities.writeToFile(filePath, fileContent,false);
					returnMessage.setMessageType(MessageType.PROMISE_ACK);
					returnMessage.setProposalNumber(message.getProposalNumber());
					returnMessage.setLockValue(message.getLockValue());

				}
				else
				{
					returnMessage.setMessageType(MessageType.PROMISE_NACK);
					returnMessage.setProposalNumber(Integer.parseInt(proposalAndLockValue[0]));
					returnMessage.setLockValue(Integer.parseInt(proposalAndLockValue[1]));			   
				}	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnMessage;
	}

}

